/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.qyer.flume.formatter;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

public class PrefixDateFormatPathManager {
  private final String defaultLogFilePrefix = "log";

  private long seriesTimestamp;
  private File baseDirectory;
  private AtomicInteger fileIndex;

  private File currentFile;
  private String prefix;

  public PrefixDateFormatPathManager() {
    seriesTimestamp = System.currentTimeMillis();
    fileIndex = new AtomicInteger();
  }

  public void config(String prefix) {
    if (prefix == null) {
      this.prefix = defaultLogFilePrefix;
    } else {
      this.prefix = prefix;
    }
  }

  public File nextFile() {
    DecimalFormat df = new DecimalFormat("00000");
    int i = fileIndex.incrementAndGet();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
    File f = new File(baseDirectory + File.separator + sdf2.format(new Date()));
    if (!f.exists()) {
      f.mkdir();
    } else {
      if (f.isFile()) {
        f.delete();
      }
    }
    String file = sdf.format(seriesTimestamp);

    currentFile = new File(f.getAbsolutePath(), prefix + "." + file + "." + df.format(i));
    return currentFile;
  }

  public File getCurrentFile() {
    if (currentFile == null) {
      return nextFile();
    }

    return currentFile;
  }

  public void rotate() {
    currentFile = null;
  }

  public File getBaseDirectory() {
    return baseDirectory;
  }

  public void setBaseDirectory(File baseDirectory) {
    this.baseDirectory = baseDirectory;
  }

  public long getSeriesTimestamp() {
    return seriesTimestamp;
  }

  public AtomicInteger getFileIndex() {
    return fileIndex;
  }

}
